/* eslint-disable no-undef */
import styles from '@/pages/main/index.less';
import { useEffect, useRef, useState } from 'react';
import { useIdleTimer } from 'react-idle-timer';

const image_normal = require('@/assets/images/icon_car_left_normal.png');
const image_done = require('@/assets/images/icon_car_left_done.png');
const image_error = require('@/assets/images/icon_car_left_error.png');
const image_center = require('@/assets/images/icon_marker_center.png');

const width = 1920 * window.scaleBase;
const regions = [
  { name: '酒泉市', lat: '39.74804', lng: '98.488189', zoom: 12 },
  { name: '嘉峪关市', lat: '', lng: '', zoom: 12 },
  { name: '瓜州县', lat: '40.511645', lng: '95.778873', zoom: 12 },
  { name: '玉门市', lat: '40.289534', lng: '97.041565', zoom: 12 },
  { name: '敦煌市', lat: '40.131384', lng: '94.662368', zoom: 12 },
  { name: '金塔县', lat: '39.975265', lng: '98.899143', zoom: 12 },
]

// const swiperInterval = 1000 * 60 * 2;
const swiperInterval = 1000 * 5;
let id_of_setInterval = null;
let loaded = false;

// test only
const carLimit = 18
const carMarkers = []
const generateNearBy = (lat, lng) => {
  return [(1 - (Math.random() * 2)) * 0.1 + parseFloat(lat), (1 - (Math.random() * 2)) * 0.1 + parseFloat(lng)];
}

const generateCarType = () => {
  const types = ['normal', 'done', 'error']
  return types[Math.floor(Math.random() * 3)];
}

const getScale = () => {
  return width / window.innerWidth;
}

const CenterTop = props => {
  // const [scale] = useState(getScale());
  const [fullScreen, setFullScreen] = useState(false);
  const map = useRef();
  const search = useRef();
  const region = useRef(0);
  const [title, setTitle] = useState(regions[region]);
  const scale = getScale();
  const height = fullScreen ? `${window.innerHeight * scale}px` : '100%';


  const handleOnIdle = event => {
    console.log('idle', loaded)
    loaded && swiper();
    id_of_setInterval = setInterval(() => {
      loaded && swiper();
    }, swiperInterval);
  }

  const handleOnActive = event => {
    console.log('active')
    id_of_setInterval && clearInterval(id_of_setInterval)
  }

  // const handleOnAction = (e) => {
  //   console.log('user did something', e)
  // }

  const { getRemainingTime, getLastActiveTime } = useIdleTimer({
    timeout: 1000 * 10,
    onIdle: handleOnIdle,
    onActive: handleOnActive,
    // onAction: handleOnAction,
    debounce: 500
  })

  const addMarker = (lat, lng, type, desc = '') => {
    let image = '';
    switch (type) {
      case 'normal':
        image = image_normal;
        break;
      case 'error':
        image = image_error;
        break;
      case 'done':
        image = image_done;
        break;
      case 'center':
      default:
        image = image_center;
        break;
    }
    // const icon = new AMap.Icon({
    //   size: new AMap.Size(25,25),
    //   image,
    //   imageSize: new AMap.Size(25,25),
    // })
    const marker = new AMap.Marker({
      // icon,
      position: [lng, lat],
      content: `<div class="marker"><img src="${image}" alt=""><div>${desc}</div></div>`
      // offset: new AMap.Pixel(-13, -30)
    });
    if(carMarkers.length >= carLimit) {
      carMarkers.shift().setMap(null);
    }

    type !== 'center' && carMarkers.push(marker);
    marker.setMap(map.current)
  }

  const swiper = () => {
    const { name, zoom, lat, lng } = regions[region.current];

    if (lat && lng) {
      map.current.setZoomAndCenter(zoom, [lng, lat]);
      setTitle(name)

      for( let i = 0; i < 3; i++) {
        const [l, r] = generateNearBy(lat, lng)
        addMarker(l, r, generateCarType(), `浙A864DT`)
      }
      region.current = (region.current + 1) % regions.length;
    }
    else {
      search.current.search(name, function (status, result) {
        // 查询成功时，result即对应匹配的POI信息
        if(result.info === 'OK') {
          const [loc] = result?.poiList?.pois;
          const { location } = loc;
          const { lat, lng } = location;
          regions[region.current].lat = lat;
          regions[region.current].lng = lng;
          map.current.setZoomAndCenter(zoom, [lng, lat]);
          addMarker(lat, lng, 'center');
          setTitle(name)
        }
        region.current = (region.current + 1) % regions.length;
      })
    }

  }

  const initMap = () => {
    map.current = new AMap.Map('map', {
      zoom: 18,
      resizeEnable: true,
      mapStyle: `amap://styles/darkblue`,
      center: [120.009506, 30.283607],
    });

    regions.forEach(({lat, lng}) => {
      if (lat && lng) addMarker(lat, lng, 'center');
    })

    AMap.plugin(['AMap.PlaceSearch', 'AMap.DistrictSearch'],function(){
      search.current = new AMap.PlaceSearch({
        city: '全国'
      })
      swiper();
      loaded = true;
    })
  }

  useEffect(() => {
    initMap();

    return () => {
      map.current = null;
      search.current = null;
      id_of_setInterval && clearInterval(id_of_setInterval);
    }
  },[])
  return <div className={styles.centerTop}>
    <div className={fullScreen ? styles.mapWrapperFullScreen : styles.mapWrapper} style={{height}}>
      <h3><span><em>{title?.slice(0,-1)}</em></span></h3>
      <div className={styles.mapFullScreenToggle} onClick={()=> setFullScreen(!fullScreen)}>
        <img src={require(`@/assets/images/icon_fullscreen_${fullScreen}.png`)} alt=""/>
      </div>
      <div className={styles.mapLegend}>
        <div>
          <img src={image_normal} alt=""/>
          <span>正常</span>
        </div>
        <div>
          <img src={image_done} alt=""/>
          <span>完成</span>
        </div>
        <div>
          <img src={image_error} alt=""/>
          <span>异常</span>
        </div>
      </div>
      <div
        id={'map'}
        className={styles.map}
        style={{
          transform: `scale(${scale})`,
          WebkitTransform: `scale(${scale})`,
        }}
      />
    </div>
  </div>
}

export default CenterTop;
